import { Injectable, UnauthorizedException } from '@nestjs/common';
import { UserService } from '~/user/user.service';
import { JwtService } from '@nestjs/jwt';
import { RegisterDto } from '@/dto/auth.dto';

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService
  ) {}

  async validateUser(username: string, pass: string): Promise<any> {
    const user = await this.userService.findOneByAccountOrMobile(username);
    if (!user) {
      throw new UnauthorizedException('用户不存在');
    }
    if (user.password === String(pass)) {
      const { password, ...result } = user.toObject();
      return result;
    }
    return null;
  }

  async validateUserById(id: string) {
    const user = await this.userService.findById(id);
    if (!user) {
      throw new UnauthorizedException('用户不存在');
    }
    const { password, ...result } = user.toObject();
    return result;
  }

  async login(user: User.UserInfo) {
    const payload = { id: user._id };
    return {
      access_token: this.jwtService.sign(payload)
    };
  }

  async register(registerDto: RegisterDto) {
    return this.userService.create(registerDto);
  }
}
